import type { AxiosError } from 'axios';
import { BACKEND_ERROR_CODE, createFlatRequest, createRequest } from '@sa/axios';
import { localStg } from '@/utils/storage';
import { getServiceBaseURL } from '@/utils/service';
import { showErrorMsg } from './shared';
import type { RequestInstanceState } from './type';
import { addToast } from "@heroui/react";
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL, otherBaseURL } = getServiceBaseURL(import.meta.env as any, isHttpProxy);

export const request = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    baseURL,
    headers: {}
  },
  {
    async onRequest(config: { headers: any; }) {
      const { headers } = config;

      // set token
      const token = localStg.get('token');
      const Authorization = token ? `Bearer ${token}` : null;
      Object.assign(headers, { Authorization });

      return config;
    },
    isBackendSuccess(response: { data: { code: any; }; }) {
      // .env 文件配置返回成功CODE
      return String(response.data.code) === import.meta.env.VITE_SERVICE_SUCCESS_CODE;
    },
    // async onBackendFail(response: { data: { msg: any; code: any; }; config: any; }) {}, // 业务报错
    transformBackendResponse(response: { data: { data: any; }; }) {
      return response.data?.data ? response.data?.data : response.data;
    },
    onError(error: AxiosError<any, any>) {
      // 请求失败的错误信息
      let message = error.message;
      let backendErrorCode = '';

      // 处理所有 HTTP 错误响应
      const { response } = error;
      if (response?.data) {
        message = response.data?.msg || message;
        backendErrorCode = response.data?.code || '';
      }

      // 跳转登录页面
      function handleLogout() {
        localStg.remove('token');
        localStg.remove('user');
        localStg.remove('email_id');
        localStg.remove('email_sender');
        window.location.href = '/login';
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        request.state.errMsgStack = request.state.errMsgStack.filter(msg => msg !== message);
      }

      // 后端服务的注销CODE, 将注销并重定向到登录页面
      const logoutCodes = import.meta.env.VITE_SERVICE_LOGOUT_CODES?.split(',') || [];
      if (logoutCodes.includes(String(response?.data?.code))) {
        handleLogout();
      }

      // 后端服务的模态注销CODE，将通过显示模态框退出
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (modalLogoutCodes.includes(backendErrorCode) && !request.state.errMsgStack?.includes(message)) {
        request.state.errMsgStack = [...(request.state.errMsgStack || []), message];

        // 阻止用户刷新页面
        window.addEventListener('beforeunload', handleLogout);

        window.$dialog?.error({
          title: 'Error',
          content: backendErrorCode,
          positiveText: '确认',
          maskClosable: false,
          onPositiveClick() {
            logoutAndCleanup();
          },
          onClose() {
            logoutAndCleanup();
          }
        });
      }

      showErrorMsg(request.state, message);
    }
  }
);

// 暂不启用
export const demoRequest = createRequest<App.Service.DemoResponse>(
  {
    baseURL: otherBaseURL.demo
  },
  {
    async onRequest(config: { headers: any; }) {
      const { headers } = config;

      // set token
      const token = localStg.get('token');
      const Authorization = token ? `Bearer ${token}` : null;
      Object.assign(headers, { Authorization });

      return config;
    },
    isBackendSuccess(response: { data: { status: string; }; }) {
      // when the backend response code is "200", it means the request is success
      // you can change this logic by yourself
      return response.data.status === '200';
    },
    async onBackendFail() {
      // when the backend response code is not "200", it means the request is fail
      // for example: the token is expired, refresh token and retry request
    },
    transformBackendResponse(response: { data: { result: any; }; }) {
      return response.data.result;
    },
    onError(error: AxiosError<any, any>) {
      // when the request is fail, you can show error message

      let message = error.message;

      // show backend error message
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.message || message;
      }

      addToast({
        title: "请求错误",
        description: message,
        color: "danger",
      })
    }
  }
);
